import { createSlice } from "@reduxjs/toolkit";
import { RootState } from "../../store";

export interface ContentData {
  id: number;
  title: string;
  author: string;
  description: string;
  fileUrl: string;
  imgUrl: string;
  demoUrl: string;
  tags: string;
  classify: string;
  createTime: number;
}

export interface ClassifyData {
  id: number;
  name: string;
}

interface HomeState {
  contents: ContentData[];
  classifys: ClassifyData[];
}
const initialState: HomeState = {
  contents: [],
  classifys: [],
};

export const homeSlice = createSlice({
  name: "home",
  initialState,
  reducers: {
    setContent(state, action) {
      state.contents = action.payload;
    },
    addContent(state, action) {
      state.contents.push(action.payload);
    },
    updateContent(state, action) {
      const content = action.payload as ContentData;

      state.contents = state.contents.map((sc) => {
   
        return +content.id === +sc.id ? content : sc;
      });
    },
    deleteContent(state, action) {
      state.contents = state.contents.filter((c) => c.id !== action.payload);
    },
    setClassify(state, action) {
      state.classifys = action.payload;
    },
  },
});

export const homeActions = homeSlice.actions;

export const selectAllContent = (state: RootState) => {
  return state.home.contents;
};

export const selectAllClassify = (state: RootState) => {
  return state.home.classifys;
};
